import Request from './request';
import {
    REQUEST_BASE_URL
} from './config';

const request = new Request({
    baseURL: REQUEST_BASE_URL,
    timeout: 15000,
});

request.interceptors.request = config => {
    const token = wx.getStorageSync('access_token');
    config.data = requestParamHandler(config.data);
    if (token) {
        config.header['authorization'] = token;
    }
    // get请求参数处理 过滤空串和null
    if (config.method === "GET") {
        for (const key in config.data) {
            const value = config.data[key]
            if (typeof value === "string" && value.trim().length === 0 || value === null) {
                delete config.data[key]
            }
        }
    }
    return config;
};

request.interceptors.response = response => {
    const {
        isSuccess,
        data,
        statusCode
    } = response;

    // 请求失败
    if (!isSuccess) {
        wx.showToast({
            title: '网络异常请重试',
            icon: 'error',
        });
        return response;
    }

    // 处理响应状态码对应逻辑
    switch (statusCode) {
        case 200:
            if (data.code !== 200) {
                wx.showToast({
                    title: data.msg,
                    icon: 'none'
                })
            }
            return data
        case 401:
            // token失效
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                duration: 1000,
                complete: () => {
                    // 清除token 重新登录
                    wx.removeStorageSync('access_token')
                    wx.removeStorageSync('user')
                    // 跳转登录页
                    wx.showModal({
                        title: '提示',
                        content: '前往登录使用完整功能',
                        success(res) {
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: '/pages/user/login/login'
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                    setTimeout(() => {
                        wx.reLaunch({
                            url: '/pages/login/login'
                        })
                    }, 1000)
                    return Promise.reject(response)
                }
            })
            break
        case 403:
            wx.showToast({
                title: '用户被禁用，请联系客服!',
                icon: 'none',
                complete: res => {
                    return Promise.reject(response)
                }
            })
            break
        case 404:
            wx.showToast({
                title: '接口不存在',
                icon: 'none',
                complete: res => {
                    return Promise.reject(response)
                }
            })
            break
        default:
            wx.showToast({
                title: '服务器错误',
                icon: 'none',
                complete: res => {
                    return Promise.reject(response)
                }
            })
    }
};

const requestParamHandler = params => {
    if (typeof params == 'object') {
        for (let key of Object.keys(params)) {
            if (params[key] == null || params[key] == undefined) {
                delete params[key];
            }
            if (params[key] instanceof Array) {
                const arr = [];
                const list = params[key];
                for (let listElement of list) {
                    const abj = requestParamHandler(listElement);
                    abj && arr.push(abj);
                }
                params[key] = arr;
            }
        }
    }
    return params;
};

export default request;